package cn.cyq.readerhelper.ocrjdk;

import com.baidu.aip.error.AipError;
import com.baidu.aip.http.AipRequest;
import com.baidu.aip.ocr.AipOcr;
import com.baidu.aip.util.Base64Util;
import com.baidu.aip.util.Util;
import org.json.JSONObject;

import java.io.IOException;
import java.util.HashMap;

public class MyAipOcr extends AipOcr {
    public MyAipOcr(String appId, String apiKey, String secretKey) {
        super(appId, apiKey, secretKey);
    }

    /**
     *
     * @param options 应该包含url字段
     * @return
     */
    public JSONObject basicAccurateGeneralUrl(HashMap<String, String> options) {
        AipRequest request = new AipRequest();
        this.preOperation(request);
        if (options != null) {
            request.addBody(options);
        }

        request.setUri("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic");
        this.postOperation(request);
        return this.requestServer(request);
    }

    public JSONObject basicAccurateGeneralPdf(String pdf, HashMap<String, String> options) {
        byte[] data = new byte[0];
        try {
            data = Util.readFileByBytes(pdf);
        } catch (IOException e) {
            e.printStackTrace();
            return AipError.IMAGE_READ_ERROR.toJsonResult();
        }
        AipRequest request = new AipRequest();
        this.preOperation(request);
        String base64Content = Base64Util.encode(data);
        request.addBody("pdf_file", base64Content);
        if (options != null) {
            request.addBody(options);
        }

        request.setUri("https://aip.baidubce.com/rest/2.0/ocr/v1/accurate_basic");
        this.postOperation(request);
        return this.requestServer(request);
    }


}
